package com.rtwo.mp3;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Random;


/**
 * Created by Administrator on 2015/5/25.
 */
@SuppressWarnings("ALL")
public class MainPage extends Activity {
    private Button play;
    private Button pause;
    private Button stop;
    private ArrayAdapter<String> songAdapter;
    private Button take_photo;
    private Button pick_photo;
    private LinearLayout mainpage;

    public static SeekBar seekBar;
    public static final int SONGSTOPS = 1;
    public static final int RANDOMSONGS = 2;
    public static final int PICK_PHOTO = 3;
    public static final int TAKE_PHOTO = 4;
    public static View selectedItem;
    private static File fileName;
    public static ListView songList;
    static MediaPlayer player;
    static TextView tips;
    public static int duration;
    private static String item;
    private static Boolean pause_flag;
    public static Drawable view_background;
    public static UIHandler handler;
    public static String playingSong;

    static {
        selectedItem = null;
        fileName = null;
        player = new MediaPlayer();
        pause_flag = false;
        //
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        take_photo = (Button) findViewById(R.id.take_photo);
        pick_photo = (Button) findViewById(R.id.pick_photo);
        mainpage = (LinearLayout) findViewById(R.id.mainpage);
        tips = (TextView) findViewById(R.id.tips);
        seekBar = (SeekBar) findViewById(R.id.seekbar);
        play = (Button) findViewById(R.id.play);
        pause = (Button) findViewById(R.id.pause);
        stop = (Button) findViewById(R.id.stop);
        songList = (ListView) findViewById(R.id.songlist);
        tips = (TextView) findViewById(R.id.tips);
        songAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getMp3());
        songList.setAdapter(songAdapter);
        songList.setSmoothScrollbarEnabled(true);
        handler = new UIHandler(this);
        songList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getId() == R.id.songlist) {
                    item = parent.getItemAtPosition(position).toString();
                    fileName = new File(Environment.getExternalStorageDirectory(), "Music/" + item);
                    if (view.equals(selectedItem)) {
                        if (!player.isPlaying()) {
                            try {
                                player.setDataSource(MainPage.this, Uri.fromFile(fileName));
                                player.prepare();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            player.stop();
                            player.reset();
                            try {
                                player.setDataSource(MainPage.this, Uri.fromFile(fileName));
                                player.prepare();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        player.start();
                        playingSong = item;//Ã¿´Îstart¸èÇúÖ®ºó,²¥·ÅµÄ¸èÇú¿Ï¶¨¾ÍÊÇÑ¡ÔñµÄ¸èÇú
                        duration = player.getDuration();
                        seekBar.setMax(duration / 1000);
                        tips.setText("ÕýÔÚ²¥·ÅµÄ¸èÇúÊÇ:" + playingSong + "   " + duration / 1000 / 60 + ":" + duration / 100 % 60);
                        view_background = view.getBackground();
                        selectedItem = view;

                    } else {
                        //Èç¹ûÔÙ´ÎÑ¡ÖÐÁËÄ³Ò»¸öview,ÄÇÃ´»¹Ô­Ö®Ç°µÄ±³¾°,Õâ¸öselectedItem°´ÕÕÂß¼­²»¿ÉÄÜÏÈÓÚselectedItem = view;µÄ´úÂëÖ´ÐÐ,´úÂëÖ´ÐÐºó²Å´ú±íÑ¡ÖÐÁËÄ³¸öview,È»ºó¾Í¿ÉÒÔ»¹Ô­±³¾°
                        if (selectedItem != null) {
                            selectedItem.setBackground(view_background);//Õâ¸öµÄview_background²»¿ÉÄÜÏÈÓÚview_background = view.getBackground();´úÂë,ËùÒÔËüµÄÖµÒ²ÊÇ´Ó¸ÃÐÐ´úÂëÖÐ»ñÈ¡µÄ,»ñÈ¡µÄ¾ÍÊÇÔ­ÏÈµÄ±³¾°
                        } else {
                            view_background = view.getBackground();//
                        }
                        //°´ÕÕÂß¼­Ê×ÏÈÖ´ÐÐµÄ¾ÍÊÇview_background = view.getBackground();µÄ´úÂë,±íÊ¾°´ÏÂÖ®ºó¸Ä±ä±³¾°,È»ºó¼ÇÂ¼°´ÏÂµÄview
                        view.setBackgroundColor(getResources().getColor(R.color.grey));
                        selectedItem = view;
                    }

                }
            }
        });
        final Thread musicTime = new songProgress(this, "MusicTime");
        musicTime.start();//¿ªÆô¼ÇÂ¼ÒôÀÖÊ±¼äÖáµÄÏß³Ì
        play.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    play.setBackground(getResources().getDrawable(R.drawable.play_foreground));
                    if (player.isPlaying() && playingSong.equals(item)) {
                        return true;
                    }//ÕâÀïµÄ´úÂë²»¿ÉÄÜÏÈÓÚ114µÄplayingSongºÍ131µÄplayingSongµÄ»ñÈ¡,ÓÃÓÚÅÐ¶ÏÊÇ·ñÎªÖ®Ç°Ñ¡ÔñµÄ¸èÇú,Èç¹ûÊÇ,Ôò²»Àí
                    else if (player.isPlaying() && !playingSong.equals(item)) {
                        //ÅÐ¶ÏÕýÔÚ²¥·ÅµÄ¸èÇúÊÇ·ñÎªÑ¡ÔñµÄ¸èÇú,Èç¹û²»ÊÇ,ÔòÔÝÍ£ÏÖÔÚµÄ¸èÇú,»»ÉÏÐÂ¸èÇú
                        player.stop();
                        player.reset();
                        try {
                            player.setDataSource(MainPage.this, Uri.fromFile(fileName));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            player.prepare();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        player.start();
                        playingSong = item;//Ã¿´Îstart¸èÇúÖ®ºó,²¥·ÅµÄ¸èÇú¿Ï¶¨¾ÍÊÇÑ¡ÔñµÄ¸èÇú
                        duration = player.getDuration();
                        seekBar.setMax(duration / 1000);
                        tips.setText("ÕýÔÚ²¥·ÅµÄ¸èÇúÊÇ:" + playingSong + "   " + duration / 1000 / 60 + ":" + duration / 100 % 60);
                        return true;
                    }
                    if (selectedItem == null) {//Èç¹ûÃ»ÓÐÑ¡Ôñ¸èÇú,ÔòÖ±½ÓÎÞ·¨Ö´ÐÐ²¥·Å°´Å¥
                        Toast.makeText(MainPage.this, "ÇëÑ¡ÔñÒ»Ê×¸èÇú", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                    if (pause_flag == false) {//ÄÜ¹»Ö´ÐÐµ½ÕâÀï,Ê×ÏÈÊÇÑ¡ÔñÁË¸èÇú,È»ºó¾ÍÊÇÃ»ÓÐ¸èÇúÕýÔÚ²¥·Å,ËùÒÔÕâÀïÊÇ×îÔ­Ê¼µÄ²¥·ÅµÄÈë¿Ú
                        try {
                            player.setDataSource(MainPage.this, Uri.fromFile(fileName));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            player.prepare();
                            if (!player.isPlaying()) {
                                player.start();
                                playingSong = item;//Ã¿´Îstart¸èÇúÖ®ºó,²¥·ÅµÄ¸èÇú¿Ï¶¨¾ÍÊÇÑ¡ÔñµÄ¸èÇú
                                duration = player.getDuration();
                                seekBar.setMax(duration / 1000);//Í¨¹ý¸èÇúµÄÊ±³¤»»Ëã³ÉseekBarµÄ×î´ó³¤¶È
                                tips.setText("ÕýÔÚ²¥·ÅµÄ¸èÇúÊÇ:" + playingSong + "   " + duration / 1000 / 60 + ":" + duration / 100 % 60);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {//ÕâÀïÊÇ°´ÏÂÁËÔÝÍ£°´Å¥µÄÊ±ºò,²¥·Å°´Å¥µÄ´¦Àí,Ö»¿ÉÄÜÓÐÁ½ÖÖÇé¿ö,1.²¥·ÅºÍÑ¡ÔñµÄ¸èÇúÒ»Ö±;2.²¥·ÅºÍÑ¡ÔñµÄ¸èÇú²»Ò»ÖÂ
                        pause_flag = false;
                        if (!playingSong.equals(item)) {
                            player.stop();
                            player.reset();
                            try {
                                player.setDataSource(MainPage.this, Uri.fromFile(fileName));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                player.prepare();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            player.start();
                            playingSong = item;//Ã¿´Îstart¸èÇúÖ®ºó,²¥·ÅµÄ¸èÇú¿Ï¶¨¾ÍÊÇÑ¡ÔñµÄ¸èÇú
                            duration = player.getDuration();
                            seekBar.setMax(duration / 1000);//Í¨¹ý¸èÇúµÄÊ±³¤»»Ëã³ÉseekBarµÄ×î´ó³¤¶È
                            tips.setText("ÕýÔÚ²¥·ÅµÄ¸èÇúÊÇ:" + playingSong + "   " + duration / 1000 / 60 + ":" + duration / 100 % 60);
                        } else {
                            player.start();//ÓÐÔÝÍ£µÄÊ±ºò,startÆðµ½ÁËresumeµÄ×÷ÓÃ
                        }
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    play.setBackground(getResources().getDrawable(R.drawable.play_background));
                }
                return true;
            }
        });
        pause.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (selectedItem == null) {
                        Toast.makeText(MainPage.this, "ÄúÉÐÎ´Ñ¡Ôñ¸èÇú", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                    pause.setBackground(getResources().getDrawable(R.drawable.pause_foreground));
                    if (player.isPlaying()) {
                        player.pause();
                        pause_flag = true;
                    } else {
                        Toast.makeText(MainPage.this, "Ã»ÓÐ¸èÇúÕýÔÚ²¥·Å", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                } else {
                    pause.setBackground(getResources().getDrawable(R.drawable.pause_background));
                }
                return true;
            }
        });
        stop.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    stop.setBackground(getResources().getDrawable(R.drawable.stop_foreground));
                    if (selectedItem == null) {
                        Toast.makeText(MainPage.this, "Ã»ÓÐÑ¡Ôñ¸èÇú", Toast.LENGTH_SHORT).show();
                        return true;
                    } else {
                        player.stop();
                        player.reset();
                    }
                } else {
                    stop.setBackground(getResources().getDrawable(R.drawable.stop_background));
                }
                return true;
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser == true) {
                    seekBar.setProgress(progress);
                    player.seekTo(progress * 1000);
                    player.start();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        pick_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                MainPage.this.startActivityForResult(intent, MainPage.PICK_PHOTO);
            }
        });
    }

    String[] getMp3() {//Í¨¹ý¶ÁÈ¡sdcardµÄmusicÎÄ¼þ»ñÈ¡¸èÇúÁÐ±íµÄ×Ö·û´®Êý×é
        File MusicFolder = new File(Environment.getExternalStorageDirectory(), "Music");
        try {
            if (!MusicFolder.exists()) {
                MusicFolder.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        MusicFileter musicFileNameFilter = new MusicFileter();
        return MusicFolder.list(musicFileNameFilter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, SongNotification.class);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(this, SongNotification.class);
        stopService(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PICK_PHOTO:
                if (resultCode == RESULT_OK) {
                }
                break;
            case TAKE_PHOTO:
                break;
            default:
                break;
        }
    }
}

//»ñÈ¡".mp3"ÎÄ¼þ
class MusicFileter implements FilenameFilter {
    @Override
    public boolean accept(File dir, String filename) {
        return filename.endsWith(".mp3");
    }
}

//Í¨¹ýhandlerµÄ·½Ê½ÔÚÏß³ÌÖÐ¶ÔUI½øÐÐÐÞ¸Ä
class UIHandler extends Handler {
    private Context context;

    public UIHandler(Context context) {
        this.context = context;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MainPage.SONGSTOPS:
                MainPage.tips.setText("ÕýÔÚ²¥·ÅµÄ¸èÇúÊÇ:" + MainPage.playingSong + "   " + MainPage.duration / 1000 / 60 + ":" + MainPage.duration / 100 % 60);
                break;
            case MainPage.RANDOMSONGS:
                MainPage.songList.smoothScrollToPosition(songProgress.randomSongId);
                View randomView = MainPage.songList.getChildAt(songProgress.randomSongId);
                MainPage.selectedItem.setBackground(MainPage.view_background);
                randomView.setBackgroundColor(context.getResources().getColor(R.color.grey));
                MainPage.selectedItem = randomView;
                break;
            default:
                break;
        }
    }
}

class songProgress extends Thread {
    private Context context;
    public static String stringForRandomSong;
    public static int randomSongId;
    public static int currentPosition;
    private Message msg;

    public songProgress(Context context, String name) {
        super(name);
        this.context = context;
    }

    @Override
    public void run() {
        Looper.prepare();
        //¸Ã·½·¨ÊÇ³õÊ¼»¯Ò»¸öÏß³Ì×÷ÎªÒ»¸öLooper¶ÔÏó,Ò»¸öÏß³ÌÖ»ÄÜÓÐÒ»¸öLooper¶ÔÏó,ËùÒÔ²»ÄÜ·ÅÔÚwhileÖÐ,LooperÊÇÔËÐÐÏß³ÌÖÐµÄMessage
        while (true) {
            if (MainPage.player.isPlaying()) {
                currentPosition = MainPage.player.getCurrentPosition() / 1000;
                if (currentPosition >= MainPage.seekBar.getMax()) {
                    MainPage.player.stop();
                    MainPage.player.reset();
                    Random r = new Random();
                    randomSongId = r.nextInt(new MainPage().getMp3().length);
                    stringForRandomSong = new MainPage().getMp3()[randomSongId];
                    Uri uriForRandomSong = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "Music/" + stringForRandomSong));
                    try {
                        MainPage.player.setDataSource(context, uriForRandomSong);
                        MainPage.player.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    MainPage.player.start();
                    MainPage.playingSong = stringForRandomSong;
                    MainPage.duration = MainPage.player.getDuration();
                    MainPage.seekBar.setMax(MainPage.duration / 1000);//Í¨¹ý¸èÇúµÄÊ±³¤»»Ëã³ÉseekBarµÄ×î´ó³¤¶È

                    //ÏëhandlerË÷Òª¶à´Î´¦Àí,Í¨¹ýÒÔÏÂµÄ·½Ê½´«Èëwhat,ÒòÎªÎÒÃÇµÄÏß³ÌÒÑ¾­Í¨¹ýLooper.prepareÉùÃ÷ÎªÒ»¸öLooper,ËùÒÔ»á·Ö¶à´Î°ÑMessageQueueµÄ¶«Î÷ÌáÈ¡³öÀ´
                    msg = new Message();
                    msg.what = MainPage.SONGSTOPS;//ÐÞ¸Ä¸¡¶¯ÎÄ×Ö
                    MainPage.handler.sendMessage(msg);

                    msg = new Message();
                    msg.what = MainPage.RANDOMSONGS;//¸Ä±äÑ¡ÖÐµÄ¸èÇú
                    MainPage.handler.sendMessage(msg);

                }
                MainPage.seekBar.setProgress(currentPosition);//ÕâÀïµÄÏß³ÌÎªÊ²Ã´¿ÉÒÔÐÞ¸ÄUI??????
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}